import sys
import os
from PyUIC.AGI_MainWindows import Ui_MainWindow
from PyQt5.QtGui import QIcon
from PyQt5 import QtWidgets,QtCore
from PyQt5.QtWidgets import QApplication,QMainWindow,QFileDialog,QSystemTrayIcon,QMenu,QAction
from AGI_Widgets.AGIPaintWidget import AGIPaintWidget
from AGI_Widgets.AGIConnectWidget import AGIConnectWidget
from AGI_Widgets.AGITestWidget import AGITestWidget
from File_Watcher import Win_FileWatcher
from MES_Watcher import MES_FileWatcher,MES_FileWatcher2
from utils.load_config import load_cfg,write_cfg

import psutil
# from AI.AI_Det import AI_DetThread
# import qdarkstyle
# from qdarkstyle.light.palette import LightPalette

class MainWindow(QMainWindow,Ui_MainWindow):
    def __init__(self,cfg,state_init,parent = None):
        super(MainWindow,self).__init__(parent)
        self.setupUi(self)
        self.Q_Main_Button.setStyleSheet("background-color: rgb(255, 255, 255) ")
        self.cfg = cfg
        self.state_init = state_init

        self.th = Win_FileWatcher().instance()
        self.mes_watch = MES_FileWatcher().instance()
        self.mes_watch.mes_coll_sig.connect(self.show_MESCOLLECTION1)
        self.mes_watch2 = MES_FileWatcher2().instance()
        self.mes_watch2.mes_coll_sig2.connect(self.show_MESCOLLECTION2)
        self.num_2 = 0
        self.num_1 = 0
        self.PaintWidget = AGIPaintWidget(self.state_init)
        self.gridLayout_4.addWidget(self.PaintWidget)
        self.PaintWidget.show()
        self.ConnectWidget = AGIConnectWidget(self.th,self.cfg,self.state_init)
        self.TestWidget = AGITestWidget()
        self.initUI()


        # param
        self.arr_list = []
        self.res_state = 0
        # self.arr_id,pad_no, img_res, width, length, c_x, c_y

        #子线程信号
        self.th.aoi_row_sig.connect(self.PaintWidget.write_aoi_tablewidget)
        self.th.ai_row_sig.connect(self.PaintWidget.write_ai_tablewidget)
        self.th.aoi_box_sig.connect(self.PaintWidget.write_roi_group)
        self.th.clear_sig.connect(self.PaintWidget.clear_tablewidget)
        self.th.image_sig.connect(self.PaintWidget.paint_image)
        self.th.aoi_image_sig.connect(self.PaintWidget.paint_aoi_image)
        self.th._3d_image_sig.connect(self.PaintWidget.paint_3d_image)
        self.th.coll__num_sig.connect(self.show_collectnum)
        # self.th.trigger.connect(self.PaintWidget.display)-

        # self.AI_Det.finishSignal.connect(self.write_tablewidget)
        # self.AI_Det.startSig.connect(self.insert_images)
        self.Q_Main_Button.clicked.connect(self.Show_connect_widget)
        self.Q_Connect_Button.clicked.connect(self.Show_connect_widget)
        self.Q_Model_Test_Button.clicked.connect(self.Show_connect_widget)
        #链接模块信号
        # self.ConnectWidget.Q_Start_CheckBox.clicked.connect(self.StartThread)
        self.PaintWidget.Start_AI.clicked.connect(self.StartThread)
        self.ConnectWidget.Q_Type_ComboBox.currentIndexChanged.connect(self.ChangeSetting)
        # self.ConnectWidget.Collection_checkBox.clicked.connect(self.Change_Save_State)
        # self.ConnectWidget.Q_MES_CheckBox.clicked.connect(self.Start_MES1_Collect)
        # self.ConnectWidget.Q_MES2_CheckBox.clicked.connect(self.Start_MES2_Collect)
        # self.ConnectWidget.Collection_checkBox.toggled.connect(self.Change_Save_State)
        self.ConnectWidget.groupbuttonBox.buttonClicked[int].connect(self.Change_Res_State)

        # self.PaintWidget.save_contour_checkBox.clicked.connect(self.Change_Save_State)
        # self.PaintWidget.save_aoibox_checkBox.clicked.connect(self.Change_Save_State)
        # self.PaintWidget.ResolutionSpinBox.valueChanged.connect(self.Change_Save_State)
        # self.Q_Type_ComboBox.currentIndexChanged.connect(self.ChangeSetting)
        self.init_AI()

    def initUI(self):
        self.textEdit = self.PaintWidget.textEdit
        # self.setCentralWidget(self.textEdit)
        sys.stdout = self.TextStream(self.textEdit)

    class TextStream:
        def __init__(self,textEdit):
            self.textEdit = textEdit
        def write(self,text):
            cursor = self.textEdit.textCursor()
            cursor.movePosition(cursor.End)
            cursor.insertText(text)
            self.textEdit.setTextCursor(cursor)
            self.textEdit.ensureCursorVisible()
        def printf(self,text):
            print(text)
    def init_AI(self):
        self.PaintWidget.Start_AI.setChecked(self.state_init["Project_State"]['AOI_Start'])
        # self.ConnectWidget.Collection_checkBox.setChecked(self.state_init["Project_State"]['Collect_Img'])
        self.StartThread()

            # self.ConnectWidget.Q_MES_CheckBox.setChecked(self.state_init["Project_State"]['MES1_Start'])
            # self.ConnectWidget.Q_MES2_CheckBox.setChecked(self.state_init["Project_State"]['MES2_Start'])
            # self.StartThread()

        # self.ConnectWidget.Q_MES_CheckBox.setChecked(self.state_init["Project_State"]['MES1_Start'])
        # self.Start_MES1_Collect()
        # self.ConnectWidget.Q_MES2_CheckBox.setChecked(self.state_init["Project_State"]['MES2_Start'])
        # self.Start_MES2_Collect()

    def Init_Setting(self):

        password, ok = QtWidgets.QInputDialog.getText(self, "Enter Passward", 'Enter Passward',
                                                      QtWidgets.QLineEdit.Password)
        # print(password,ok)
        if password == self.state_init["Passward"] and ok:
            return True
        else:
            return False

    def Init_Testing(self):

        password, ok = QtWidgets.QInputDialog.getText(self, "Enter Passward", 'Enter Passward',
                                                      QtWidgets.QLineEdit.Password)
        # print(password,ok)
        if password == '111111' and ok:
            return True
        else:
            return False

    def Show_connect_widget(self):
        sender = self.sender().text()
        if sender == 'PathSetting' and self.Init_Setting():
            # self.Init_Setting()
            self.Q_Main_Button.setStyleSheet(None)
            self.Q_Model_Test_Button.setStyleSheet(None)
            self.Q_Connect_Button.setStyleSheet("background-color: rgb(255, 255, 255)")
            self.gridLayout_4.addWidget(self.ConnectWidget)
            self.PaintWidget.hide()
            self.TestWidget.hide()
            self.ConnectWidget.show()
        elif sender=='MainWindow':
            self.Q_Connect_Button.setStyleSheet(None)
            self.Q_Model_Test_Button.setStyleSheet(None)
            self.Q_Main_Button.setStyleSheet("background-color: rgb(255, 255, 255)")
            self.ConnectWidget.hide()
            self.TestWidget.hide()
            self.PaintWidget.show()
        elif sender == 'TestModel' and self.Init_Testing():

            self.Q_Connect_Button.setStyleSheet(None)
            self.Q_Model_Test_Button.setStyleSheet("background-color: rgb(255, 255, 255)")
            self.Q_Main_Button.setStyleSheet(None)
            self.gridLayout_4.addWidget(self.TestWidget)
            self.ConnectWidget.hide()
            self.PaintWidget.hide()
            self.TestWidget.show()
    def show_mainwindow(self):
        self.Q_Connect_Button.setStyleSheet(None)
        self.Q_Main_Button.setStyleSheet("background-color: rgb(255, 255, 255)")
        self.ConnectWidget.hide()
        self.PaintWidget.show()

    def CheckPath(self,path):
        if os.path.exists(path) and path != '':
            return True
        else:
            return False

    def show_collectnum(self,num):
        self.PaintWidget.DataNum_lineEdit.setText(str(num))
    def show_MESCOLLECTION2(self,num):
        self.num_2 = num
        self.mes_num = self.num_2+self.num_1
        self.PaintWidget.MESNum_lineEdit.setText(str(self.mes_num))
    def show_MESCOLLECTION1(self, num):
        self.num_1 = num
        self.mes_num = self.num_2+self.num_1
        self.PaintWidget.MESNum_lineEdit.setText(str(self.mes_num))
    def Start_AI_Thread(self):
        if self.PaintWidget.Start_AI.isChecked():
            if not self.CheckPath(self.ConnectWidget.AOI_Folder):
                self.PaintWidget.Start_AI.setChecked(False)
                self.state_init["Project_State"]['AOI_Start'] = False
                write_cfg('./config/settings.yaml', self.state_init)
                QtWidgets.QMessageBox.warning(self, 'Warning', 'AOI_Folder Not Exist!!!',
                                              QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.Yes)

                return False
            if not self.CheckPath(self.ConnectWidget.MES_Folder):
                self.PaintWidget.Start_AI.setChecked(False)
                self.state_init["Project_State"]['AOI_Start'] = False
                write_cfg('./config/settings.yaml', self.state_init)
                QtWidgets.QMessageBox.warning(self,'Warning','MES_Front Folder Not Exist!!!',QtWidgets.QMessageBox.Yes,QtWidgets.QMessageBox.Yes)
                return False

                # return False
            if not self.CheckPath(self.ConnectWidget.Img_Connection_Folder):

                self.PaintWidget.Start_AI.setChecked(False)
                self.state_init["Project_State"]['AOI_Start'] = False
                write_cfg('./config/settings.yaml', self.state_init)
                QtWidgets.QMessageBox.warning(self, 'Warning', 'Data_Collection Folder Not Exist!!!',
                                              QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.Yes)

                return False


            # self.ConnectWidget.Collection_checkBox.setChecked(True)
            product_type = self.ConnectWidget.Q_Type_ComboBox.currentText()
            self.th.add_watchlist(self.ConnectWidget.AOI_Folder, self.ConnectWidget.AI_Folder,
                                  self.ConnectWidget.Img_Connection_Folder,product_type,
                                  self.ConnectWidget.OCR_Root,self.ConnectWidget.POT_Root,
                                  self.ConnectWidget.AI_OK_Folder,self.ConnectWidget.AIOK_checkBox.isChecked())
            self.th.set_save_state(self.PaintWidget.save_aoibox_checkBox.isChecked(),self.PaintWidget.save_contour_checkBox.isChecked(),
                                   True,self.res_state,self.ConnectWidget.AIOK_checkBox.isChecked())
            self.th.Start()
            #MES1
            self.mes_watch.add_watchlist(self.ConnectWidget.MES_Folder, self.ConnectWidget.MES_Collect_Folder,
                                         self.ConnectWidget.Img_Connection_Folder)
            self.mes_watch.Start()
            # MES2


            self.state_init["Project_State"]['AOI_Start'] = True
            if self.CheckPath(self.ConnectWidget.MES_Folder2):
                self.mes_watch2.add_watchlist(self.ConnectWidget.MES_Folder2, self.ConnectWidget.RearMESBackup_Folder,
                                              self.ConnectWidget.Img_Connection_Folder)
                self.mes_watch2.Start()
            # else:
            #     QtWidgets.QMessageBox.warning(self, 'Warning', 'MES_Rear Folder Not Exist!!!\nWon`t Collect MES_Rear!!!',
            #                                   QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.Yes)
            self.PaintWidget.StateButton.setText("运行中")
            self.PaintWidget.StateButton.setStyleSheet("background-color:green")
        else:
            self.th.Stop()
            self.mes_watch.Stop()
            self.mes_watch2.Stop()
            self.state_init["Project_State"]['AOI_Start'] = False
            self.PaintWidget.StateButton.setText("停止")
            self.PaintWidget.StateButton.setStyleSheet("background-color:red")


        write_cfg('./config/settings.yaml', self.state_init)
    def StartThread(self):

        is_start = self.Start_AI_Thread()



    def Start_MES1_Collect(self):
        if self.PaintWidget.Start_AI.isChecked():
            # if not self.CheckPath(self.ConnectWidget.MES_Folder):
            #     QtWidgets.QMessageBox.warning(self,'Warning','MES_Front Folder Not Exist!!!',QtWidgets.QMessageBox.Yes,QtWidgets.QMessageBox.Yes)
            #
            #     # self.ConnectWidget.Q_MES_CheckBox.setChecked(False)
            #     # self.state_init["Project_State"]['MES1_Start'] = False
            #     # write_cfg('./config/settings.yaml', self.state_init)
            #     return

            self.mes_watch.add_watchlist(self.ConnectWidget.MES_Folder,self.ConnectWidget.MES_Collect_Folder,self.ConnectWidget.Img_Connection_Folder)
            self.mes_watch.Start()
            # self.state_init["Project_State"]['MES1_Start'] = True
        else:
            self.mes_watch.Stop()
        #     self.state_init["Project_State"]['MES1_Start'] = False
        # write_cfg('./config/settings.yaml', self.state_init)

    def Start_MES2_Collect(self):
        if self.PaintWidget.Start_AI.isChecked():
            # if not self.CheckPath(self.ConnectWidget.MES_Folder2):
            #     QtWidgets.QMessageBox.warning(self, 'Warning', 'MES_Rear Folder Not Exist!!!',
            #                                   QtWidgets.QMessageBox.Yes, QtWidgets.QMessageBox.Yes)
            #
            #     # self.ConnectWidget.Q_MES2_CheckBox.setChecked(False)
            #     # self.state_init["Project_State"]['MES2_Start'] = False
            #     # write_cfg('./config/settings.yaml', self.state_init)
            #     return
            self.mes_watch2.add_watchlist(self.ConnectWidget.MES_Folder2, self.ConnectWidget.RearMESBackup_Folder,
                                          self.ConnectWidget.Img_Connection_Folder)
            self.mes_watch2.Start()
            # self.state_init["Project_State"]['MES2_Start'] = True
        else:
            self.mes_watch2.Stop()
        #     self.state_init["Project_State"]['MES2_Start'] = False
        # write_cfg('./config/settings.yaml', self.state_init)

    def Change_Res_State(self,idx):
        self.res_state=idx
        print(self.res_state)
        self.th.set_save_state(self.PaintWidget.save_aoibox_checkBox.isChecked(),
                               self.PaintWidget.save_contour_checkBox.isChecked(),
                               self.ConnectWidget.Collection_checkBox.isChecked(),
                               self.res_state, self.ConnectWidget.AIOK_checkBox.isChecked())
    # def Change_Save_State(self):
    #     self.th.set_save_state(self.PaintWidget.save_aoibox_checkBox.isChecked(),
    #                            self.PaintWidget.save_contour_checkBox.isChecked(),
    #                            self.ConnectWidget.Collection_checkBox.isChecked(),
    #                            self.res_state, self.PaintWidget.ResolutionSpinBox.value())
    #     self.state_init["Project_State"]['Collect_Img'] =self.ConnectWidget.Collection_checkBox.isChecked()
    #     write_cfg('./config/settings.yaml', self.state_init)

    def ChangeSetting(self):
        if self.ConnectWidget.Q_Type_ComboBox.currentIndex()==0:
            self.ConnectWidget.Q_AOI_Folder_Button.setText('SPI_Path')
            # self.Q_Type_ComboBox.setCurrentIndex(0)
            self.ConnectWidget.AOI_Folder = self.cfg["PemtronSPI"]["SPI_Path"]
            self.ConnectWidget.Q_AOI_Folder_LineEdit.setText(self.ConnectWidget.AOI_Folder)
            self.ConnectWidget.AI_Folder = self.cfg["PemtronSPI"]["AI_Path"]
            self.ConnectWidget.Q_AI_Folder_LineEdit.setText(self.ConnectWidget.AI_Folder)
            self.ConnectWidget.Img_Connection_Folder = self.cfg["PemtronSPI"]["Data_Collection"]
            self.ConnectWidget.IP_Adress = self.cfg["PemtronSPI"]["DataBaseIP"][1]
            self.ConnectWidget.MES_Folder = self.cfg["PemtronSPI"]["MES_Front"]
            self.ConnectWidget.MES_Front_LlineEdit.setText(self.ConnectWidget.MES_Folder)
            self.ConnectWidget.MES_Folder2 = self.cfg["PemtronSPI"]["MES_Rear"]
            self.ConnectWidget.MES_Rear_LlineEdit.setText(self.ConnectWidget.MES_Folder2)
            self.ConnectWidget.MES_Collect_Folder = self.cfg["PemtronSPI"]["FrontMESBackup"]
            self.ConnectWidget.FrontMESBackup_LineEdit.setText(self.ConnectWidget.MES_Collect_Folder)
            self.ConnectWidget.RearMESBackup_Folder = self.cfg["PemtronSPI"]["RearMESBackup"]
            self.ConnectWidget.RearMESBackup_LineEdit.setText(self.ConnectWidget.RearMESBackup_Folder)
            self.ConnectWidget.AI_OK_Folder = self.cfg["PemtronSPI"]["AI_OK_Folder"]
            self.ConnectWidget.Q_AIOK_Collection_LineEdit.setText(self.self.ConnectWidget.AI_OK_Folder)
            self.state_init["UI_State"] = 0

            # self.ConnectWidget.Q_AOI_Image_lineEdit.hide()
            # self.ConnectWidget.Q_AOI_Image_pushButton.hide()
            # self.ConnectWidget.Q_AI_Folder_Button.hide()
            # self.ConnectWidget.Q_AI_Folder_LineEdit.hide()
            self.PaintWidget.tabWidget.setCurrentIndex(0)
        elif self.ConnectWidget.Q_Type_ComboBox.currentIndex()==1:
            self.ConnectWidget.Q_AOI_Folder_Button.setText('AOI_Path')
            # self.Q_Type_ComboBox.setCurrentIndex(1)
            self.ConnectWidget.AOI_Folder = self.cfg["PemtronAOI"]["AOI_Path"]
            self.ConnectWidget.Q_AOI_Folder_LineEdit.setText(self.ConnectWidget.AOI_Folder)
            self.ConnectWidget.AI_Folder = self.cfg["PemtronAOI"]["AI_Path"]
            self.ConnectWidget.Q_AI_Folder_LineEdit.setText(self.ConnectWidget.AI_Folder)
            self.ConnectWidget.Img_Connection_Folder = self.cfg["PemtronAOI"]["Data_Collection"]
            self.ConnectWidget.IP_Adress = self.cfg["PemtronAOI"]["DataBaseIP"][1]
            self.ConnectWidget.MES_Folder = self.cfg["PemtronAOI"]["MES_Front"]
            self.ConnectWidget.MES_Front_LlineEdit.setText(self.ConnectWidget.MES_Folder)
            self.ConnectWidget.MES_Folder2 = self.cfg["PemtronAOI"]["MES_Rear"]
            self.ConnectWidget.MES_Rear_LlineEdit.setText(self.ConnectWidget.MES_Folder2)
            self.ConnectWidget.MES_Collect_Folder = self.cfg["PemtronAOI"]["FrontMESBackup"]
            self.ConnectWidget.FrontMESBackup_LineEdit.setText(self.ConnectWidget.MES_Collect_Folder)
            self.ConnectWidget.RearMESBackup_Folder = self.cfg["PemtronAOI"]["RearMESBackup"]
            self.ConnectWidget.RearMESBackup_LineEdit.setText(self.ConnectWidget.RearMESBackup_Folder)
            self.ConnectWidget.AI_OK_Folder = self.cfg["PemtronAOI"]["AI_OK_Folder"]
            self.ConnectWidget.Q_AIOK_Collection_LineEdit.setText(self.self.ConnectWidget.AI_OK_Folder)
            # self.ConnectWidget.AI_Image_Folder = self.cfg["PemtronAOI"]["AOI图片路径"]
            self.state_init["UI_State"] = 1

            # self.ConnectWidget.Q_AOI_Image_lineEdit.setText(self.ConnectWidget.AI_Image_Folder)
            # self.ConnectWidget.Q_AOI_Image_lineEdit.hide()
            # self.ConnectWidget.Q_AOI_Image_pushButton.hide()
            # self.ConnectWidget.Q_AI_Folder_Button.show()
            # self.ConnectWidget.Q_AI_Folder_LineEdit.show()
            self.PaintWidget.tabWidget.setCurrentIndex(1)
        write_cfg('./config/settings.yaml',self.state_init)
        write_cfg('./config/path_settings.yaml', self.cfg)

    def changeEvent(self, event):
        if event.type() == QtCore.QEvent.WindowStateChange:
            if self.windowState() & QtCore.Qt.WindowMinimized:
                event.ignore()
                """
                这里插入最小化窗口的处理逻辑代码
                """
                self.setWindowFlags(QtCore.Qt.SplashScreen | QtCore.Qt.FramelessWindowHint)
                self.showMinimized()
                # self.close()
                return

    def closeEvent(self, event):
        reply = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Question, self.tr("Tips"), self.tr("Is Running\nSure to Quit？"), QtWidgets.QMessageBox.NoButton, self)
        yr_btn = reply.addButton(self.tr("Qiut"), QtWidgets.QMessageBox.YesRole)
        no_btn = reply.addButton(self.tr("Not Quit"), QtWidgets.QMessageBox.NoRole)
        reply.exec_()
        if reply.clickedButton() ==yr_btn:
            password,ok = QtWidgets.QInputDialog.getText(self,"Enter Passward",'Enter Passward',QtWidgets.QLineEdit.Password)
            # print(password,ok)
            if password == self.state_init["Passward"] and ok:
                event.accept()
                QtWidgets.qApp.quit()
                sys.exit(app.exec_())
            else:
                event.ignore()

        else:
            event.ignore()
            # 最小化到托盘
        #     self.setWindowFlags(QtCore.Qt.SplashScreen | QtCore.Qt.FramelessWindowHint)
        #     self.showMinimized()
        # else:
        #     event.ignore()
    # def ChangeCollection(self):
    #     self.th.Collection_State(self.ConnectWidget.Collection_checkBox.isChecked())

################################托盘功能###################################
class TrayIcon(QSystemTrayIcon):
    def __init__(self, MainWindow,passward,parent=None):
        super(TrayIcon,self).__init__(parent)
        self.ui = MainWindow
        self.passward = passward
        self.createMenu()

    def createMenu(self):
        self.menu = QMenu()
        self.showAction1 = QAction("Show",self,triggered = self.show_window)
        self.showAction2 = QAction("Quit",self,triggered = self.quit)

        self.menu.addAction(self.showAction1)
        self.menu.addAction(self.showAction2)
        self.setContextMenu(self.menu)

        self.setIcon(QIcon("./QSS/1.ico"))
        self.icon = self.MessageIcon()

        #吧鼠标点击图标的信号和槽链接
        self.activated.connect(self.onIconClicked)

    def show_window(self):
        # 若是最小化，则先正常显示窗口，再变为活动窗口（暂时显示在最前面）
        self.ui.showNormal()
        self.ui.activateWindow()
        self.ui.setWindowFlags(QtCore.Qt.Window)
        self.ui.show()

    def quit(self):

        password,ok = QtWidgets.QInputDialog.getText(self.ui,"Enter Passward",'Enter Passward',QtWidgets.QLineEdit.Password)
        # print(password,ok)
        if password == self.passward and ok:

            QtWidgets.qApp.quit()

        else:
           return


        # 鼠标点击icon传递的信号会带有一个整形的值，1是表示单击右键，2是双击，3是单击左键，4是用鼠标中键点击

    def onIconClicked(self, reason):
        if reason == 2 or reason == 3:
            # self.showMessage("Message", "skr at here", self.icon)
            if self.ui.isMinimized() or not self.ui.isVisible():
                # 若是最小化，则先正常显示窗口，再变为活动窗口（暂时显示在最前面）
                self.ui.showNormal()
                self.ui.activateWindow()
                self.ui.setWindowFlags(QtCore.Qt.Window)
                self.ui.show()
            else:
                # 若不是最小化，则最小化
                self.ui.showMinimized()
                self.ui.setWindowFlags(QtCore.Qt.SplashScreen| QtCore.Qt.FramelessWindowHint)

                self.ui.show()

# class Dialog(QtWidgets.QMainWindow):
#     def __init__(self,MainWindow,parent=None):
#         super(Dialog, self).__init__(parent)
#     def closeEvent(self, event):
#         reply = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Question, self.tr("提示"), self.tr("汝妻子我养之，汝勿虑之。\n 汝特么确定要退出吗？"), QtWidgets.QMessageBox.NoButton, self)
#         yr_btn = reply.addButton(self.tr("是的我要退出"), QtWidgets.QMessageBox.YesRole)
#         reply.addButton(self.tr("最小化到托盘"), QtWidgets.QMessageBox.NoRole)
#         reply.exec_()
#         if reply.clickedButton() == yr_btn:
#             event.accept()
#             QtWidgets.qApp.quit()
#             # sys.exit(app.exec_())
#         else:
#             event.ignore()
#             # 最小化到托盘
#             MainWindow.setWindowFlags(QtCore.Qt.SplashScreen | QtCore.Qt.FramelessWindowHint)
#             MainWindow.showMinimized()

# import logging
#
#
# def logger(file_log):
#     '''
#     打日志
#     :param file_log: 日志文件名，类型string；
#     '''
#     # 创建一个loggger，并设置日志级别
#     logger = logging.getLogger()
#     logger.setLevel(logging.DEBUG)
#
#     # 创建一个handler，用于写入日志文件，并设置日志级别，mode:a是追加写模式，w是覆盖写模式
#     fh = logging.FileHandler(filename=file_log, encoding='utf-8', mode='a')
#     fh.setLevel(logging.INFO)
#
#     # 创建一个handler，用于将日志输出到控制台，并设置日志级别
#     ch = logging.StreamHandler()
#     ch.setLevel(logging.INFO)
#
#     # 定义handler的输出格式
#     formatter = logging.Formatter(
#         '%(asctime)s-%(name)s-%(filename)s-[line:%(lineno)d]''-%(levelname)s-[日志信息]: %(message)s')
#     fh.setFormatter(formatter)
#     ch.setFormatter(formatter)
#     # 给logger添加handler
#     logger.addHandler(fh)
#     logger.addHandler(ch)
#
#     return logger

class MessageBox(QtWidgets.QWidget):#继承自父类QtWidgets.QWidget
    def __init__(self,parent = None):#parent = None代表此QWidget属于最上层的窗口,也就是MainWindows.
        QtWidgets.QWidget.__init__(self)#因为继承关系，要对父类初始化

    def show_message(self,message = 'the exe is running!'):
        QtWidgets.QMessageBox.warning(self, "Warning", message, QtWidgets.QMessageBox.Cancel)
#内容要长，太短会导致标题显示不全！
import datetime
if __name__=='__main__':
    current_time = datetime.datetime.now()

    time_str = current_time.strftime("%Y%m%d")
    # print(type(time_str))  # 得到str

    due_date = datetime.date(2025, 1, 1)
    due_date_str = due_date.strftime("%Y%m%d")
    if int(due_date_str)<int(time_str):
        app = QApplication(sys.argv)

        window = MessageBox()
        window.show_message(message='试用时间已到期！')
        # window.show()
        sys.exit(app.exec_())
        # cmd = 'taskkill /pid ' + "pidd" + ' /f'  # 输入关闭名称命令

        os.system(cmd)

    # second_date = datetime.date(2022, 3, 1)
    # logger = logger('./logging.log')
    # logger.info("----------------日志输出----------------\n")
    pids = psutil.pids()  # 获取所有进程PID
    list = []  # 空列表用来存储PID名称
    i = 0  # 计数，程序名称出现的次数
    for pid in pids:  # 遍历所有PID进程
        p = psutil.Process(pid)  # 得到每个PID进程信息
        list.append(p.name())  # 将PID名称放入列表
        s = str(p.name())  # 将PID名称转换成字符串进行判断
        # print(s)
        if s == "Main_AGI.exe":  # “123.exe”你要防多开进程的名称
            i += 1

    if i < 2:
        cfg = load_cfg('./config/path_settings.yaml')
        state_init = load_cfg('./config/settings.yaml')
        passward = state_init["Passward"]

        app = QApplication(sys.argv)
        # window = MessageBox()
        # window.show_message()
        myWin = MainWindow(cfg,state_init)
        # myWin = Dialog(myWin)
        #
        # app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
        # # or in new API
        # app.setStyleSheet(qdarkstyle.load_stylesheet(qt_api='pyqt5',palette=LightPalette()))
        # myWin.paintEngine()
        # myWin.showMaximized()
        # myWin.setWindowFlags(QtCore.Qt.SplashScreen | QtCore.Qt.FramelessWindowHint)
        myWin.show()
        ti = TrayIcon(myWin,passward)
        ti.show()

        sys.exit(app.exec_())
    else:
        app = QApplication(sys.argv)

        window = MessageBox()
        window.show_message()
        sys.exit(app.exec_())
        pidd = os.getpid()  # 获取当前PID名称

        cmd = 'taskkill /pid ' + "pidd" + ' /f'  # 输入关闭名称命令

        os.system(cmd)